#!/usr/bin/perl

use DBI;
use strict;

my $dsn="dbi:Pg:dbname=flux_monitoring;host=localhost;port=5432";
my $user="postgres";
my $password="";

# Set up a connection to the database listing the RPFITS files that need to be
# processed.
my $dbh=DBI->connect($dsn,$user,$password,{ RaiseError => 0, AutoCommit => 1});

my $get_plot=$ARGV[0];

my $sth_command="SELECT rpfits_file,description FROM rpfits_summary WHERE rpfits_file='$get_plot'";
print "[$sth_command]\n";
my $sth=$dbh->prepare($sth_command);
$sth->execute;

while (my ($rpfits_file,$description)=$sth->fetchrow()){
    print "found RPFITS file $rpfits_file\n";
    print $description;
    print "\n";
}
$sth->finish;

$sth_command="SELECT lo_export(rpfits_summary.summary_plot,".
    "'/var/lib/postgresql/$get_plot\_summary.png') ".
    "FROM rpfits_summary WHERE rpfits_file='$get_plot'";
print "[$sth_command]\n";
$sth=$dbh->prepare($sth_command);
$sth->execute;
$sth->finish;

my $scp_command="scp -P 2222 postgres\@localhost:$get_plot\_summary.png .";
system $scp_command;
my $ssh_command="ssh -p 2222 postgres\@localhost rm $get_plot\_summary.png";
system $ssh_command;

